﻿using CKS.Core.Framework;
using CKS.PLC.Action.Subscription.OP080;
using CKS.PLC.Core.Cache;
using FreeSql;
using Infrastructure;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ZR.Infrastructure;
using ZR.Model.Models.ProductionControl;
using ZR.Service.IService.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP71
{
    /// <summary>
    /// 动作编号-2\4
    /// 钎焊炉结束加热
    /// </summary>
    public class DB1200_Work02Action : PLCAction
    {
        
        public DB1200_Work02Action(DecodeValue _value) : base(_value)
        {
           
        }
        public override void Execute()
        {
            var replayDB = 1200;
            var replayAction = Value.Position.ActionId;
            var result = Value.Value.ToInt();
            
            var replayPos = Value.GetReplyPosition(replayDB, replayAction, 0);
         
            if (result == 1)
            {
                /*
                 创建热处理记录表 cks_heat_treatment
                 料架信息 开始时间 结束时间 状态 1开始 10完成 ， 创建时间
                 创建钎焊炉加热记录表
                 */
                //要查询和当前数据位置相关的记录
           
                var locationId = Value.Position.LocationId;
                var model = conn.Select<CksBrazingRecord>()
                    .Where(a=>a.LocationId == locationId).OrderByDescending(a => a.Id).First();

                if (model?.Status == 1  )
                {
                    model.Status = 10;
                    model.EndTime = DateTime.Now;
                    conn.Update<CksBrazingRecord>().SetSource(model).UpdateColumns(a => new { a.Status, a.EndTime })
                        .ExecuteAffrows();

                    //更新明细结束时间
                    //保存数据到动态表、
                    if (model?.Status == 10)
                    {
                        var shelfCells = conn.Select<CksShelfForFixture>().Where(a => a.ShelfId == model.MaterialRackNo).ToList();
                        SaveProductInfo(model, shelfCells);
                    }
                }
                

                EventBus.AddLog($"OP71钎焊炉结束加热，炉号{model?.FurnaceNo}");
                AckWriteInt16(replayPos, 1);
            }
            else
            {
               
                AckWriteInt16(replayPos, 0);
                logger.LogInformation($"OP71钎焊炉结束加热信号-重置");
            }
        }

        private void SaveProductInfo(CksBrazingRecord main,List<CksShelfForFixture> cells)
        {
            string endtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            foreach (var item in cells)
            {
                if(item.FixtureId>0)
                {
                    //架子上的夹具号大于0说明存放了夹具，查询夹具上绑定的条码信息
                    var fixture =conn.Select<CksFixtureinfo>().Where(a => a.FixtureId == item.FixtureId).First();
                    if(fixture == null)
                    {
                        continue;
                    }

                    //码不为空存入OP90_Data表
                    var vt =conn.Select<CksVirtualTable>().Where(a => a.TableName == "OP71_Data").First();
                    var columnQuery = conn.Select<CksVirtualColumn>().Where(a => a.TableId == vt.Id).OrderBy(a => a.Sequence);
                    var columns = columnQuery.ToList();
                    var table = ServiceCommon.GetFreesqlTableInfo(vt, columns);
                    var model = conn.Select<object>().AsType(table.Type)
                         .Where(" BatchNo = @BatchNo AND MaterialRackNo = @MaterialRackNo AND FixtureNo = @FixtureNo "
                         , new { BatchNo = main.BatchNo, MaterialRackNo = item.ShelfId, FixtureNo = fixture.FixtureId })
                         .First().Adapt<Dictionary<string, object>>();


                    var dict = new Dictionary<string, object>();
                    dict["OutTime"] = endtime;
                    dict["Id"] = model["Id"];
                    UpdateDynamicTableData(table, dict);


                }
            }
        }
    }
}
